import pymysql
import toml
import threading
from dbutils.pooled_db import PooledDB
from pymysql.cursors import DictCursor
from typing import Dict, Any

class DatabasePoolManager:
    """数据库连接池管理器（单例模式）"""
    _instance = None
    _lock = threading.Lock()
    _pool = None
    _config = None
    
    def __new__(cls, config_path: str = 'conf/dao_config.toml'):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self, config_path: str = 'conf/dao_config.toml'):
        if self._pool is None:
            self._config = self._load_config(config_path)
            self._pool = self._create_connection_pool()
    
    def _load_config(self, config_path: str) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                return toml.load(f)
        except Exception as e:
            raise Exception(f"配置文件加载失败: {e}")
    
    def _create_connection_pool(self):
        """创建数据库连接池"""
        db_config = self._config['database']
        return PooledDB(
            creator=pymysql,
            maxconnections=db_config.get('pool_size', 10),
            mincached=2,
            maxcached=5,
            maxshared=3,
            blocking=True,
            maxusage=None,
            setsession=[],
            ping=0,
            host=db_config['host'],
            port=db_config['port'],
            user=db_config.get('username', db_config.get('user')),  # 兼容两种配置
            password=db_config['password'],
            database=db_config['database'],
            charset=db_config.get('charset', 'utf8mb4'),
            cursorclass=DictCursor,
            autocommit=True
        )
    
    def get_connection(self):
        """获取数据库连接"""
        return self._pool.connection()
    
    def get_config(self):
        """获取配置"""
        return self._config
    
    def reload_config(self, config_path: str = 'conf/dao_config.toml'):
        """重新加载配置"""
        with self._lock:
            self._config = self._load_config(config_path)
            self._pool = self._create_connection_pool()